<?php
class ModelAccountCustomer extends Model {
	public function addCustomer($data) {
		$this->event->trigger('pre.customer.add', $data);

		if (isset($data['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($data['customer_group_id'], $this->config->get('config_customer_group_display'))) {
			$customer_group_id = $data['customer_group_id'];
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}


		$this->load->model('account/customer_group');

		$customer_group_info = $this->model_account_customer_group->getCustomerGroup($customer_group_id);



		$this->db->query("INSERT INTO " . DB_PREFIX . "customer SET customer_group_id = '" . (int)$customer_group_id . "', store_id = '" . (int)$this->config->get('config_store_id') . "', firstname = '" . $this->db->escape($data['firstname'])  . "', telephone = '" . $this->db->escape($data['telephone']) . "', salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "', newsletter = '" . (isset($data['newsletter']) ? (int)$data['newsletter'] : 0) . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', status = '1', approved = '" . (int)!$customer_group_info['approval'] . "', image ='" . $this->db->escape($data['image']) . "', open_id = '" . $this->db->escape($data['open_id']) . "',  date_added = NOW()");

		$customer_id = $this->db->getLastId();

		$this->event->trigger('post.customer.add', $customer_id);

		return $customer_id;
	}


	public function autoAddCustomer($data){
	    $this->event->trigger('pre.customer.add', $data);

	    if (isset($data['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($data['customer_group_id'], $this->config->get('config_customer_group_display'))) {
	        $customer_group_id = $data['customer_group_id'];
	    } else {
	        $customer_group_id = $this->config->get('config_customer_group_id');
	    }


	    $this->load->model('account/customer_group');

	    $customer_group_info = $this->model_account_customer_group->getCustomerGroup($customer_group_id);



	    $this->db->query("INSERT INTO " . DB_PREFIX . "customer SET customer_group_id = '" . (int)$customer_group_id . "', store_id = '" . (int)$this->config->get('config_store_id') . "', firstname = '" . $this->db->escape($data['firstname'])  . "', newsletter = '" . (isset($data['newsletter']) ? (int)$data['newsletter'] : 0) . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', status = '1', approved = '" . (int)!$customer_group_info['approval'] . "', image ='" . $this->db->escape($data['wx_image']) . "',wx_image ='" . $this->db->escape($data['wx_image']) . "', open_id = '" . $this->db->escape($data['open_id']) . "',  date_added = NOW()");

	    $customer_id = $this->db->getLastId();

	    $this->event->trigger('post.customer.autoadd', $customer_id);

	    return $customer_id;

	}

	public function editCustomerByWxInfo($data){
	    $this->event->trigger('pre.customer.edit', $data);


	    $this->db->query("UPDATE " . DB_PREFIX . "customer SET firstname = '" . $this->db->escape($data['firstname']) . "', image = '" . $this->db->escape($data['image']) . "', open_id = '" . $this->db->escape($data['open_id']) . "' WHERE customer_id = '" . (int)$data['customer_id'] . "'");

	    $this->event->trigger('post.customer.edit',$data['customer_id']);
	}

    //分步编辑用户信息
	public function editCustomerInfo($data,$step,$is_addpoints=false,$points=0){
        if($step==1){
            $this->event->trigger('pre.customer.edit', $data);
            $this->db->query("UPDATE " . DB_PREFIX . "customer SET lastname = '" . $this->db->escape($data['lastname']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', birthday = '" . $this->db->escape($data['birthday']) . "',grade_time = '".$this->db->escape($data['grade_time'])."',country_id = '".(int)$data['country_id']."',zone_id = '".(int)$data['zone_id']."' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
            $this->event->trigger('post.customer.edit',$data['customer_id']);
        }else if($step==2){
            $this->event->trigger('pre.customer.edit', $data);
            $this->db->query("DELETE FROM " . DB_PREFIX . "customer_hardware WHERE customer_id = '" . (int)$this->customer->getId() . "'");
            $this->db->query("INSERT INTO " . DB_PREFIX . "customer_hardware SET hardware_code = '" . $this->db->escape($data['hardware_code'])  . "', customer_id = '" . (int)$this->customer->getId() . "', buy_time = '" . $this->db->escape($data['buy_time']) . "', date_added = now() ");
        }else{

        }
	}

	public function editCustomer($data) {
		$this->event->trigger('pre.customer.edit', $data);

		$customer_id = $this->customer->getId();

		$this->db->query("UPDATE " . DB_PREFIX . "customer SET firstname = '" . $this->db->escape($data['firstname']) . "', lastname = '" . $this->db->escape($data['lastname']) . "', email = '" . $this->db->escape($data['email']) . "', telephone = '" . $this->db->escape($data['telephone']) . "', fax = '" . $this->db->escape($data['fax']) . "', custom_field = '" . $this->db->escape(isset($data['custom_field']) ? serialize($data['custom_field']) : '') . "' WHERE customer_id = '" . (int)$customer_id . "'");

		$this->event->trigger('post.customer.edit', $customer_id);
	}

	public function cookerApply($data)
	{
	    $this->event->trigger('pre.customer.edit', $data);

	    $customer_id = $this->customer->getId();

	    $customer_fields = "is_cooker='".(int)$data['is_cooker']."',country='".(int)$data['country']."',zone='".(int)$data['zone']."',lat='" . $this->db->escape($data['lat']) . "',lng='" . $this->db->escape($data['lng']) . "',description='" . $this->db->escape($data['description']) . "',cook_year=DATE_SUB(NOW(),INTERVAL '" . $this->db->escape($data['years']) . "' YEAR)";

	    $this->db->query("UPDATE " . DB_PREFIX . "customer SET ".$customer_fields." WHERE customer_id = '" . (int)$customer_id . "'");

	    $this->event->trigger('post.customer.edit', $customer_id);
	}

	public function editCustomerByKeyValue($key,$value) {

	    $customer_id = $this->customer->getId();
	    $keys = array('name','nickname','phone','description','image','password','alipay','device_token','token');
	    if(in_array($key, $keys))
	    {
	        if($key == 'nickname')
	        {
	            $key = 'firstname';
	        }
	        else if($key=='name')
	        {
	            $key = "lastname";
	        }
	        else if($key == 'phone')
	        {
	            $key = "email";
	        }


	        if($key == 'password')
	        {
	            $this->db->query("UPDATE " . DB_PREFIX . "customer SET salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($value)))) . "' WHERE customer_id = '" . (int)$customer_id . "'");
	        }
	        else
	       {
	            $this->db->query("UPDATE " . DB_PREFIX . "customer SET ".$key." = '" . $this->db->escape($value) . "' WHERE customer_id = '" . (int)$customer_id . "'");
	        }
	    }


	}

	public function editPassword($email, $password) {
		$this->event->trigger('pre.customer.edit.password');

		$this->db->query("UPDATE " . DB_PREFIX . "customer SET salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($password)))) . "' WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		$this->event->trigger('post.customer.edit.password');
	}

	public function editPasswordByPhone($phone, $password) {
	    $this->event->trigger('pre.customer.edit.password');

	    $this->db->query("UPDATE " . DB_PREFIX . "customer SET salt = '" . $this->db->escape($salt = substr(md5(uniqid(rand(), true)), 0, 9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($password)))) . "' WHERE LOWER(telephone) = '" . $this->db->escape(utf8_strtolower($phone)) . "'");

	    $this->event->trigger('post.customer.edit.password');
	}

	public function editNewsletter($newsletter) {
		$this->event->trigger('pre.customer.edit.newsletter');

		$this->db->query("UPDATE " . DB_PREFIX . "customer SET newsletter = '" . (int)$newsletter . "' WHERE customer_id = '" . (int)$this->customer->getId() . "'");

		$this->event->trigger('post.customer.edit.newsletter');
	}

	public function getCustomer($customer_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$customer_id . "'");
        $cutomer_info = $query->row;
		return $cutomer_info;
	}

	public function getCustomerByEmail($email) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE LOWER(email) = '" . $this->db->escape(utf8_strtolower($email)) . "' or  LOWER(telephone) = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		return $query->row;
	}

     public function getCustomerByOpenId($open_id) {
         $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE open_id = '" . $this->db->escape($open_id) . "'");

         return $query->row;
	}

	public function getCustomerByToken($token) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE token = '" . $this->db->escape($token) . "' AND token != ''");

		$this->db->query("UPDATE " . DB_PREFIX . "customer SET token = ''");

		return $query->row;
	}

	public function getTotalCustomersByPhone($email) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "customer WHERE telephone = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		return $query->row['total'];
	}

	public function getIps($customer_id) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "customer_ip` WHERE customer_id = '" . (int)$customer_id . "'");

		return $query->rows;
	}

	public function isBanIp($ip) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "customer_ban_ip` WHERE ip = '" . $this->db->escape($ip) . "'");

		return $query->num_rows;
	}

	public function addLoginAttempt($email) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer_login WHERE email = '" . $this->db->escape(utf8_strtolower((string)$email)) . "' AND ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "'");

		if (!$query->num_rows) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "customer_login SET email = '" . $this->db->escape(utf8_strtolower((string)$email)) . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', total = 1, date_added = '" . $this->db->escape(date('Y-m-d H:i:s')) . "', date_modified = '" . $this->db->escape(date('Y-m-d H:i:s')) . "'");
		} else {
			$this->db->query("UPDATE " . DB_PREFIX . "customer_login SET total = (total + 1), date_modified = '" . $this->db->escape(date('Y-m-d H:i:s')) . "' WHERE customer_login_id = '" . (int)$query->row['customer_login_id'] . "'");
		}
	}

	public function getLoginAttempts($email) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "customer_login` WHERE email = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		return $query->row;
	}

	public function deleteLoginAttempts($email) {
		$this->db->query("DELETE FROM `" . DB_PREFIX . "customer_login` WHERE email = '" . $this->db->escape(utf8_strtolower($email)) . "'");
	}

	public function updateCustomerByWx($customer_id,$data){
	    $this->db->query("UPDATE " . DB_PREFIX . "customer SET firstname = '".$this->db->escape($data['firstname'])."', wx_image = '".$this->db->escape($data['image'])."' ,image = '".$this->db->escape($data['image'])."' , open_id ='".$this->db->escape($data['open_id'])."' WHERE customer_id = '" . (int)$customer_id . "'");

	}

	//添加用户手持优学派学习机
	public function addCustomerHardWare($data){
	    $this->deleteCustomerHardWare($this->customer->getId());
        $this->db->query("INSERT INTO " . DB_PREFIX . "customer_hardware SET  customer_id = '".(int)$this->customer->getId()."' ,date_added=now()");

	    if(isset($data['hardware_code'])&&!empty($data['hardware_code'])){
            $this->db->query("UPDATE ". DB_PREFIX . "customer_hardware SET  hardware_code= '".$this->db->escape($data['hardware_code'])."' WHERE customer_id='".(int)$this->customer->getId()."'");
        }
        if(isset($data['buy_time'])&&!empty($data['buy_time'])){
            $this->db->query("UPDATE ". DB_PREFIX . "customer_hardware SET  buy_time= '".$this->db->escape($data['buy_time'])."' WHERE customer_id='".(int)$this->customer->getId()."'");
        }
        if(isset($data['hardware_name'])&&!empty($data['hardware_name'])){
            $this->db->query("UPDATE ". DB_PREFIX . "customer_hardware SET  hardware_name= '".$this->db->escape($data['hardware_name'])."' WHERE customer_id='".(int)$this->customer->getId()."'");
        }
        if(isset($data['buy_address'])&&!empty($data['buy_address'])){
            $this->db->query("UPDATE ". DB_PREFIX . "customer_hardware SET  buy_address= '".$this->db->escape($data['buy_address'])."',network_id = '".(int)$data['network_id']."' WHERE customer_id='".(int)$this->customer->getId()."'");
        }
	    if(isset($data['hardware_code'])&&!empty($data['hardware_code'])&&isset($data['buy_time'])&&!empty($data['buy_time'])&&isset($data['hardware_name'])&&!empty($data['hardware_name'])&&isset($data['buy_address'])&&!empty($data['buy_address'])){
            $this->db->query("UPDATE ". DB_PREFIX . "customer SET  customer_group_id= 3 WHERE customer_id='".(int)$this->customer->getId()."'");
        }

	}

	public function  getAreaInfo($id){
	    if($id==0){
            $query = $this->db->query("SELECT  * FROM `" . DB_PREFIX . "tab_area` WHERE `father` = 0  ");
        }else{
            $query = $this->db->query("SELECT  * FROM `" . DB_PREFIX . "tab_area` WHERE `father` = '".(int)$id."'");
        }

        return $query->rows;
    }

	public function deleteCustomerHardWare($customer_id){
	    $this->db->query("DELETE FROM `" . DB_PREFIX . "customer_hardware` WHERE `customer_id` = '" . (int)$customer_id . "'");
	}

	public function getCustomerHardWare($customer_id){
	    $query = $this->db->query("SELECT DISTINCT * FROM `" . DB_PREFIX . "customer_hardware` WHERE `customer_id` = '" . (int)$customer_id . "'");
	    return $query->row;
	}

   public function getCustomerChild($customer_id){
       $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "customer_child` WHERE `customer_id` = '" . (int)$customer_id . "'");
       return $query->rows;

   }

   public function addCustomerChild($data,$customer_id){
	    $this->db->query("INSERT INTO " . DB_PREFIX . "customer_child SET  birthday= '" . $data['birthday'] . "',school='".$this->db->escape($data['school'])."',grade='".$data['grade']."',name='".$this->db->escape($data['name'])."',customer_id='".(int)$customer_id."',date_added=now()");
	}

	public function deleteCustomerChild($customer_id){
	    $this->db->query("DELETE FROM `" . DB_PREFIX . "customer_child` WHERE `customer_id` = '" . (int)$customer_id . "'");
	}

	public function updateCustomerByYx($data,$customer_id){
	    $this->db->query("UPDATE " . DB_PREFIX . "customer SET firstname = '".$this->db->escape($data['firstname'])."', email = '".$this->db->escape($data['email'])."' , telephone ='".$this->db->escape($data['telephone'])."' WHERE customer_id = '" . (int)$customer_id . "'");

	}


	public function updateParent($data){
        $this->db->query("UPDATE " . DB_PREFIX . "customer SET lastname = '".$this->db->escape($data['lastname'])."', country_id = '".(int)$data['country_id']."' , zone_id ='".(int)$data['zone_id']."',district_id = '".(int)$data['district_id']."',telephone = '".$this->db->escape($data['telephone'])."' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
    }



    public function AddRecommend($data){

        $this->db->query("INSERT INTO " . DB_PREFIX . "recommend_user SET  firstname= '" . $this->db->escape($data['firstname']) . "', lastname = '".$this->db->escape($data['lastname'])."', customer_id='".(int)$this->customer->getId()."',telephone='".$this->db->escape($data['telephone'])."',date_added=now()");
    }

    public function updateRecommend($data){

        $this->db->query("UPDATE " . DB_PREFIX . "customer SET recommend_telephone = '".$this->db->escape($data['telephone'])."' WHERE customer_id = '" . (int)$this->customer->getId() . "'");
    }


    public function getRecommendUser(){
        $query = $this->db->query("SELECT DISTINCT * FROM `" . DB_PREFIX . "recommend_user` WHERE `customer_id` = '" . (int)$this->customer->getId() . "'");
        return $query->row;
    }


}